<script setup lang="ts">
import { ref } from 'vue';
import CustomNavBar from './components/CustomNavBar.vue';
import CategoryPanel from './components/CategoryPanel.vue';
import HotPanel from './components/HotPanel.vue';
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/apis/home';
import type { BannerItem, CategoryItem, HotItem } from '@/types/home';
import { onLoad } from '@dcloudio/uni-app';
import IndexSkeleton from './index.skeleton.vue';
import { useXtxRecommand } from '@/composables/useXtxRecommand';

// 首页轮播图
const homeBannerList = ref<BannerItem[]>();
const getHomeBanner = async () => {
  const response = await getHomeBannerAPI().request;
  homeBannerList.value = response.result;
};

// 主页分类
const homeCategoryList = ref<CategoryItem[]>();
const getHomeCategory = async () => {
  const response = await getHomeCategoryAPI().request;
  homeCategoryList.value = response.result;
};

// 热门商品
const homeHotList = ref<HotItem[]>();
const getHomeHot = async () => {
  const response = await getHomeHotAPI().request;
  homeHotList.value = response.result;
};

// 采用推荐商品hook
const { xtxRecommandRef, xtxRecommandLoadMore, xtxRecommandRefresh } = useXtxRecommand();

// 回到顶部
const scrollTop = ref(0);
const backToTop = () => {
  scrollTop.value = 0;
};

// 是否处于刷新中
const refreshing = ref(false);

// 刷新页面数据
const onRefresh = async () => {
  refreshing.value = true;
  // 刷新所有组件数据
  try {
    await Promise.all([getHomeBanner(), getHomeCategory(), getHomeHot(), xtxRecommandRefresh()]);
  }
  finally {
    refreshing.value = false
  }
};

onLoad(async () => {
  try {
    await Promise.all([getHomeBanner(), getHomeCategory(), getHomeHot()]);
  }
  catch (e) {
    uni.showToast({ title: '当前网络状况不佳，请稍后重试~', icon: 'none' });
  }
});
</script>

<template>
  <scroll-view v-if="homeBannerList && homeCategoryList && homeHotList" class="viewport" scroll-y
    :show-scrollbar="false" :scroll-top="scrollTop" refresher-enabled refresher-background="#27ba9b"
    :refresher-triggered="refreshing" @scrolltolower="() => xtxRecommandLoadMore()" @refresherrefresh="onRefresh">
    <!-- 此处必须使用一个view包含所有子组件，否则sticky失效 -->
    <view>
      <CustomNavBar />
      <XtxSwiper :bannerList="homeBannerList" />
      <CategoryPanel :categoryList="homeCategoryList" />
      <HotPanel :hotList="homeHotList" />
      <XtxRecommand ref="xtxRecommandRef" />
    </view>
  </scroll-view>
  <!-- 未加载完成显示骨架屏 -->
  <IndexSkeleton v-else />
</template>

<style lang="scss">
.viewport {
  width: 100vw;
  height: 100vh;
}
</style>
